package com.common.server.common.exception;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.common.server.common.response.ResponseVo;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * 描述：公共系统异常处理
 * <p>
 * 作者：HuTongFu
 * 时间：2019/7/12 15:51
 */
@ControllerAdvice
public class CustomerExceptionHandler {

    private Logger logger = (Logger) LoggerFactory.getLogger("error");

    {
        logger.setLevel(Level.ERROR);
    }

    /**
     * 捕捉其他所有异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseVo handleException(Exception e, HttpServletRequest requests) {
        logger.error("错误日志记录");
        Map dataMap = requests.getParameterMap();
        Set keySet = dataMap.keySet();
        for (Object key : keySet) {
            String[] datas = (String[]) dataMap.get(key);
            StringBuilder value = new StringBuilder();
            for (String data : datas) {
                value.append(data).append(",");
            }
            logger.error("Param:" + key + " = " + value.substring(0, value.length() - 1));//将请求参数保存在日志中
        }
        logger.error(ExceptionUtils.getStackTrace(e));  // 记录错误信息
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "系统内部错误";
        }
        return ResponseVo.error(msg);
    }

}
